package com.hertz.iris.view.matchalarm;

import java.io.IOException;

import javax.inject.Inject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import butterknife.InjectView;
import butterknife.OnClick;

import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
import com.github.kevinsawicki.wishlist.Toaster;
import com.hertz.iris.Injector;
import com.hertz.iris.IrisApplication;
import com.hertz.iris.IrisServiceProvider;
import com.hertz.iris.R;
import com.hertz.iris.core.MatchAlarmService;
import com.hertz.iris.pojo.MatchAlarm;
import com.hertz.iris.pojo.MatchNba;
import com.hertz.iris.receiver.ConnectivyBroadcastReceiver;
import com.hertz.iris.ui.IrisFragmentActivity;
import com.hertz.iris.util.BundleKeys;
import com.hertz.iris.util.Constants;
import com.hertz.iris.util.DateUtil;
import com.hertz.iris.util.Strings;
import com.hertz.iris.util.Utils;
import com.hertz.iris.view.matchalarm.MatchAlarmConditionSelectorFragment.OnMatchAlarmConditionSelectListener;
import com.hertz.iris.view.matchalarm.RingSelectorFrag.OnRingSelectorListener;
import com.hertz.iris.view.matchalarm.VolumeSelectorFrag.OnVolumeSelectListener;

public class MatchAlarmActivity extends IrisFragmentActivity implements OnVolumeSelectListener,OnRingSelectorListener,OnMatchAlarmConditionSelectListener {
	
	@InjectView(R.id.guest_name)
	TextView guestNameText;
	@InjectView(R.id.host_name)
	TextView hostNameText;
	@InjectView(R.id.match_day_text)
	TextView matchDayText;
	@InjectView(R.id.match_time_text)
	TextView matchTimeText;
	@InjectView(R.id.volume_ll)
	LinearLayout volumeLL;
	@InjectView(R.id.volume)
	TextView volumeText;
	@InjectView(R.id.ring_ll)
	LinearLayout ringLL;
	@InjectView(R.id.ring)
	TextView ringText;
	@InjectView(R.id.cancel_btn)
	Button cancelBtn;
	@InjectView(R.id.ok_btn)
	Button okBtn;
	@InjectView(R.id.trash_btn)
	Button trashBtn;
	@InjectView(R.id.ok_btn_progress)
	ProgressBar okBtnProgress;
	@InjectView(R.id.wave_tb)
	ToggleButton waveTb;
	@InjectView(R.id.period_notice)
	ToggleButton periodNoticeTb;
	
	@InjectView(R.id.networkBanner)
	LinearLayout networkBanner;
	
	private MatchNba matchNba;
	private MatchAlarm matchAlarm;
	private String currentFragmentTag;
	private Bundle arguments = new Bundle();
	private String CUR_FRAG_TAG_KEY = "currentFragmentTagKey";
	private BroadcastReceiver connectivyBroadcastReceiver;
	
	@Inject protected IrisServiceProvider serviceProvider;
	@Inject protected MatchAlarmService matchAlarmService;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.matchalarm);
		
		initView(savedInstanceState);
		Injector.inject(this);
		
		//check network
		if(Utils.checkNetwork(getBaseContext())){
        	networkBanner.setVisibility(View.GONE);
        }else{
        	networkBanner.setVisibility(View.VISIBLE);
        }
        connectivyBroadcastReceiver = new ConnectivyBroadcastReceiver(networkBanner);
        IntentFilter filter = new IntentFilter();  
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
        registerReceiver(connectivyBroadcastReceiver, filter);
	}
	
	private void initView(Bundle saveBundle){
		okBtnProgress.setVisibility(View.GONE);
		cancelBtn.setTypeface(IrisApplication.getInstance().getTypeface());
		okBtn.setTypeface(IrisApplication.getInstance().getTypeface());
		trashBtn.setTypeface(IrisApplication.getInstance().getTypeface());
		
		
		if(saveBundle != null){
			matchAlarm = (MatchAlarm)saveBundle.getSerializable(BundleKeys.MatchAlarmBundleKeys.MATCH_ALARM_KEY);
			matchNba = (MatchNba)saveBundle.getSerializable(BundleKeys.MatchAlarmBundleKeys.MATCH_KEY);
			currentFragmentTag = saveBundle.getString(CUR_FRAG_TAG_KEY);
		}else{
			matchAlarm = (MatchAlarm)getIntent().getExtras().getSerializable(BundleKeys.MatchAlarmBundleKeys.MATCH_ALARM_KEY);
			matchNba = (MatchNba)getIntent().getExtras().getSerializable(BundleKeys.MatchAlarmBundleKeys.MATCH_KEY);
			
			currentFragmentTag = MatchAlarmConditionSelectorFragment.class.getSimpleName();
			if(matchAlarm == null){
				matchAlarm = new MatchAlarm();
//				matchAlarm.setUid(Constants.DEFAULT_UID);
				matchAlarm.setRingName(getResources().getString(R.string.no_ring));
				matchAlarm.setWave(Constants.MATCH_ALARM.DEFAULT_WAVE);
				matchAlarm.setVolume(Constants.MATCH_ALARM.DEFAULT_VALUME);
				matchAlarm.setAgain(Constants.MATCH_ALARM.DEFAULT_AGAIN);
				matchAlarm.setMid(matchNba.getId());
				matchAlarm.setPeriod(Constants.MATCH_ALARM.DEFAULT_PERIOD);
				matchAlarm.setRemain(Constants.MATCH_ALARM.DEFAULT_REMAIN);
				matchAlarm.setScoreDiff(Constants.MATCH_ALARM.DEFAULT_SCORE_DIFF);
				matchAlarm.setStatus(Constants.MATCH_ALARM.DEFAULT_SATAUS);
				matchAlarm.setEveryQuarter(Constants.MATCH_ALARM.DEFAULT_EVERY_QUARTER);
			}
		}
		guestNameText.setText(matchNba.getGuestTeam().getTeamName());
		hostNameText.setText(matchNba.getHostTeam().getTeamName());
		matchDayText.setText(matchNba.getMatchDay());
		matchTimeText.setText(matchNba.getMatchTime());
		volumeText.setText(matchAlarm.getVolume() + "%");
        ringText.setText(Strings.isBlank(matchAlarm.getRingName()) ? "无" : matchAlarm.getRingName());
        waveTb.setChecked(matchAlarm.getWave());
        periodNoticeTb.setChecked(matchAlarm.getEveryQuarter());
		if(matchAlarm.getId() == null){
			trashBtn.setVisibility(View.GONE);
		}
		if(!Strings.isBlank(currentFragmentTag)){
			try {
				replaceFragment(Class.forName(this.getClass().getPackage().getName() + "." + currentFragmentTag));
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		initSelected();
	}
	
	private void replaceFragment(Class fragClass) {
		FragmentManager fm = getSupportFragmentManager();
		Fragment fragment = fm.findFragmentByTag(fragClass.getSimpleName());
		FragmentTransaction ft = fm.beginTransaction();
        ft.setCustomAnimations(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
        try {
			fragment = (Fragment)fragClass.newInstance();
			fragment.setArguments(getArguments());
			ft.replace(R.id.matchalarm_fragment_container,fragment, fragClass.getSimpleName());
			currentFragmentTag = fragClass.getSimpleName();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
        ft.commit();
	}
	
	@OnClick(R.id.period_notice)
	void periodNoticeToggleButtonOnClick(){
		matchAlarm.setEveryQuarter(periodNoticeTb.isChecked());
	}
	
	@OnClick(R.id.wave_tb)
	void waveToggleButtonOnClick(){
		if(waveTb.isChecked()){
			Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);  
			vibrator.vibrate(500); 
		}
		matchAlarm.setWave(waveTb.isChecked());
	}
	
	@OnClick(R.id.ring_ll)
	void ringLLOnClick(){
		if(ringLL.isSelected()){
			ringLL.setSelected(false);
			replaceFragment(MatchAlarmConditionSelectorFragment.class);
		}else{
			ringLL.setSelected(true);
			replaceFragment(RingSelectorFrag.class);
		}
		clearOtherSelectedState(R.id.ring_ll);
	}
	
	@OnClick(R.id.volume_ll)
	void volumeLLOnClick(){
		if(volumeLL.isSelected()){
			volumeLL.setSelected(false);
			replaceFragment(MatchAlarmConditionSelectorFragment.class);
		}else{
			volumeLL.setSelected(true);
			replaceFragment(VolumeSelectorFrag.class);
		}
		clearOtherSelectedState(R.id.volume_ll);
	}
	
	@Override
	public void matchAlarmConditionSelectListener(byte period, byte remain) {
		// TODO Auto-generated method stub
		matchAlarm.setPeriod(period);
		matchAlarm.setRemain(remain);
	}

	@Override
	public void volumeSelectListener(byte volumeValue) {
		volumeText.setText(String.format(getResources().getString(R.string.volume),volumeValue));
		matchAlarm.setVolume(volumeValue);
	}
	
	@Override
	public void ringSelectorListener(byte index,String title, String uri) {
		ringText.setText(title);
		matchAlarm.setRingName(title);
		matchAlarm.setRingUri(uri);
	}
	
	private Bundle getArguments(){
		arguments.putSerializable(BundleKeys.MatchAlarmBundleKeys.MATCH_ALARM_KEY, matchAlarm);
		arguments.putString(CUR_FRAG_TAG_KEY, currentFragmentTag);
		arguments.putSerializable(BundleKeys.MatchAlarmBundleKeys.MATCH_KEY, matchNba);
		return arguments;
	}
	
	private void clearOtherSelectedState(int viewId){
		if(viewId != volumeLL.getId()){
			volumeLL.setSelected(false);
		}
		if(viewId != ringLL.getId()){
			ringLL.setSelected(false);
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle bundle){
		super.onSaveInstanceState(bundle);
		bundle.putAll(getArguments());
	}
	@Override
	public void onBackPressed() {
		if(currentFragmentTag.equals(MatchAlarmConditionSelectorFragment.class.getSimpleName()))
			super.onBackPressed();
		else{
			replaceFragment(MatchAlarmConditionSelectorFragment.class);
	        volumeLL.setSelected(false);
	        ringLL.setSelected(false);
		}
	}
	
	@OnClick(R.id.cancel_btn)
	void cancelBtnClick(){
		super.onBackPressed();
	}
	
	@OnClick(R.id.ok_btn)
	void okBtnClick(){
		matchAlarm.setUtime(System.currentTimeMillis());
		String matchTimeStr = matchDayText.getText().toString() + " " + matchTimeText.getText().toString();
		matchAlarm.setMatchTime(DateUtil.string2Time(matchTimeStr, DateUtil.YMD_HM));
		//save or update
		matchAlarm.setCtime(System.currentTimeMillis());
		Runnable runnable = new PostMatchAalarmThread(matchAlarm);
		okBtnProgress.setVisibility(View.VISIBLE);
		new Thread(runnable).start();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(connectivyBroadcastReceiver);
	} 
	
	private void superOnBackPressed(){
		super.onBackPressed();
	}
	
	private Handler mHandler = new Handler(){  
        
        public void handleMessage(Message msg) {  
        	okBtnProgress.setVisibility(View.GONE);
            switch (msg.what) {  
            case -1:
            	Toaster.showShort(MatchAlarmActivity.this, Constants.ToastMessage.NETWORK_ERROR);
            	break;
            case 1:  
            	superOnBackPressed();
                break;
            case 0:
            	Toaster.showShort(MatchAlarmActivity.this, Constants.ToastMessage.POST_MATCH_ALARM_ERROR);
            }  
        };  
    };  
	
    private class PostMatchAalarmThread implements Runnable{  
    	private MatchAlarm matchAlarm;
    	public PostMatchAalarmThread(MatchAlarm matchAlarm){
    		this.matchAlarm = matchAlarm;
    	}
        @Override  
        public void run() {  
              
            Message message = new Message(); 
            message.what = 0;
            boolean result = false;
            try {
            	if(matchAlarm.getRingName().equals(getResources().getString(R.string.no_ring)))
            		matchAlarm.setRingName("");
				result = matchAlarmService.saveOrUpdateMatchAlarm(matchAlarm, MatchAlarmActivity.this);
				if(result)
					message.what = 1;
			} catch (HttpRequestException hre){
				hre.printStackTrace();
				message.what = -1;
			}catch (IOException ioe){
				ioe.printStackTrace();
			} catch (Exception e){
				e.printStackTrace();
			}
            MatchAlarmActivity.this.mHandler.sendMessage(message);
        }     
    }  
    
	private void initSelected(){
		if(currentFragmentTag.equals(MatchAlarmConditionSelectorFragment.class.getSimpleName())){
			return;
		}
		if(currentFragmentTag.equals(RingSelectorFrag.class.getSimpleName())){
			ringLL.setSelected(true);
			return;
		}
		if(currentFragmentTag.equals(VolumeSelectorFrag.class.getSimpleName())){
			volumeLL.setSelected(true);
			return;
		}
	}
}
